import { v4 as uuidv4 } from 'uuid';
export default {
  use(app, knex){

    //新增设备
    app.post('/device/add', async function(req, res){

      //同一通道下设备不得超过127个
       const counts = await knex('device')
      .where('parent_id', '=', req.body.parent_id)
      .count('parent_id as total')
      if(counts[0].total >= 127){
        res.send({
          code: 1,
          message: '同一通道下设备不得超过127个'
        })
        return;
      }
      //是否命名重复
      const sameNames = await  knex('device')
      .where('parent_id', '=', req.body.parent_id)
      .andWhere('name', '=', req.body.name)
      if(sameNames.length > 0){
        res.send({
          code: 1,
          message: `设备名称重复请修改后重新提交`,
        })
        return;
      }  

      knex('device')
      .insert({id: uuidv4(), ...req.body})
      .then(row=>{
        res.send({
          code: 0,
          message: '新增设备成功'
        })
      })
      .catch(err=>{
        console.log(err)
        res.send({
          code: 1,
          message: JSON.stringify(err)
        })
      })  
    
    })


    //查询设备
    app.post('/device', function(req, res){
      knex('device')
      .where({'parent_id': req.body.parent_id})
      .select('*').then(rows=>{
        res.send({
          code: 0,
          data: rows
        })
      })  
      .catch(err => {
        console.log(err)
        res.send({
          code: 1,
          message: err
        })
      })
    })

    
    //删除设备
    app.post('/device/del', function(req, res){
      knex
      .raw(`PRAGMA foreign_keys=ON`)
      .then(() => {
        knex
        .raw(`delete from device where id="${req.body.id}"`)
        .then( rows =>{
          res.send({
            code: 0,
            data: '删除设备成功'
          })
        })
      })
    })

    
    //更新设备
    app.post('/device/update', function(req, res){
      const data = req.body;
      const id = data.id;
      delete data.id;
      knex('device')
      .where('id', '=', id)
      .update({
        ...data
      })
      .then(row => {
        res.send({
          code: 0,
          data: '更新设备成功'
        })
      })
      .catch(err => {
        res.send({
          code: 1,
          message: err
        })
      })
    })
  }
}

